import axios from "axios";
import qs from 'qs';
import {BRStorage} from "./brStorage";

axios.defaults.timeout = 50000; //请求超时时间

//请求拦截
axios.interceptors.request.use(
    (config) => {
        config.headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        // config.headers.token = user.token;
        return config;
    },
    (error) => {
        return Promise.reject(error);
    },
    (error) => {
        return Promise.reject(error);
    }
);

//响应拦截
axios.interceptors.response.use(
    function (res) {
        return res;
    },
    (error) => {
        let msg = error.message.includes('timeout') ? '网络请求超时，请稍候再试' : '网络请求异常，请稍候再试';
        this.BRDialog(msg);
        return Promise.reject(error);
    }
);


/**
 * 封装请求
 * @param url
 * @param params
 * @param method
 * @param loading
 * @param isFetchBRAjaxData
 * @returns {Promise}
 */
export function apiAxios(url = "", params = {}, method = "post", loading = true, isFetchBRAjaxData = true) {
    let paramsD
    if (isFetchBRAjaxData) {
        paramsD = fetchBRAjaxData(params);
    } else {
        paramsD = params;
    }
    if (loading) {
        this.BRShowLoad("加载中...", 1000000);
    }

    method = method.toUpperCase(); //转成大写
    let config = {
        method: method,
        url: url,
        transformRequest: [
            function (data) {
                return qs.stringify(paramsD);
            }
        ],
    };

    if (paramsD.download) {
        config.responseType = 'blob';
    }

    return new Promise((resolve, reject) => {
        axios(config)
            .then((res) => {
                if (loading) {
                    this.BRHideLoad();
                }
                if (res && res.status === 200) {
                    resolve(res.data);
                }
            })
            .catch((response) => {
                if (loading) {
                    this.BRHideLoad();
                }
                reject(response);
            });
    });
}



function fetchBRAjaxData(paramsDataJson) {
    let commonUrlData = {
        userToken: BRStorage.getStorage(BRStorage.KeyUserToken()),
        runRomSystem: BRStorage.getStorage(BRStorage.KeyRunRomSystem()),
        channelCode: BRStorage.getStorage(BRStorage.KeyChannelCode()),
        gameId: BRStorage.getStorage(BRStorage.KeyGameID()),
        sdkVersionCode: BRStorage.getStorage(BRStorage.KeyBRSDKVersionCode()),
    };
    return brExtendJson(commonUrlData, paramsDataJson);
}

function brExtendJson(source, target) {
    for (let key in target) {
        let strKey = source[key];
        if (strKey === null || strKey === undefined || strKey === '') {
            source[key] = target[key];
            continue;
        }
    }
    return source;
}